package com.suse.service.community.controller;

import com.suse.service.community.constant.TopicConstant;
import com.suse.service.community.entity.Comment;
import com.suse.service.community.kafka.Event;
import com.suse.service.community.kafka.EventProducer;
import com.suse.service.community.service.CommentService;
import com.suse.service.community.util.RedisUtil;
import com.suse.service.community.util.UserHolder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;

/**
 * <p>
 * 评论前端控制器
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-09-01 11:33
 */
@Controller
@RequestMapping("/comment")
public class CommentController {

    @Resource
    private CommentService commentService;

    @Resource
    private EventProducer eventProducer;

    @Resource
    private RedisTemplate<Object,Object> redisTemplate;

    @PostMapping("/save/{postId}/{entityUserId}")
    public String save(@PathVariable("postId") int postId,@PathVariable("entityUserId") int entityUserId,Comment comment) {
        int userId = UserHolder.getUser().getId();
        comment.setUserId(userId);
        comment.setStatus(0);
        commentService.save(comment);
        // 触发评论事件
        Event event = new Event();
        event.setTopic(TopicConstant.COMMENT);
        event.put("userId",userId);
        event.put("entityType",comment.getEntityType());
        event.put("entityId",comment.getEntityId());
        event.put("postId",postId);
        event.put("entityUserId",entityUserId);
        eventProducer.fireEvent(event);
        // 将帖子ID放入Redis的待刷新集合中 无序不重复集合
        redisTemplate.opsForSet().add(RedisUtil.getNeedRefreshScorePostsKey(),postId);
        return "redirect:/discuss/detail/" + postId;
    }

}
